//
// Created by denglibin on 2019/6/18 0018.
//
/**实现array_list**/
#ifndef __16ARRAY_LIST___
#define __16ARRAY_LIST___
#include <stdio.h>
#include <stdlib.h>
#include <memory.h>
typedef struct array_list
{
    unsigned int limit; //集合最大大小
    unsigned int size;  //元素个数
    int *data;          //数据
} ArrayList;

/**
 * 创建
 * @return
 */
ArrayList *createArrayList();
/**
 * 添加
 * @param arrayList
 * @param data
 * @return
 */
int add(ArrayList *arrayList, int data);

/**
 * 获取
 * @param index
 * @return
 */
int get(ArrayList *arrayList, int index);
/**
 * 释放空间
 * @param arrayList
 */
void freeList(ArrayList *arrayList);

int main16()
{
    ArrayList *list = createArrayList();

    for (int i = 0; i < 50; i++)
    {
        add(list, i);
    }
    for (int i = 0; i < list->size; i++)
    {
        printf("%d : %d\n", i, get(list, i));
    }
    freeList(list);
    return 0;
}
ArrayList *createArrayList()
{
    ArrayList *p = (ArrayList *)calloc(1, sizeof(ArrayList));
    p->limit = 16;
    p->data = (int *)calloc(p->limit, sizeof(int));
    p->size = 0;
    return p;
}
int add(ArrayList *arrayList, int data)
{
    if (arrayList->size == arrayList->limit)
    {
        arrayList->limit = arrayList->limit + arrayList->limit / 2;
        //扩容
        arrayList->data = (int *)realloc(arrayList->data, arrayList->limit * sizeof(int));
    }
    arrayList->data[arrayList->size] = data;
    // printf("%d\n", arrayList->data[arrayList->size]);
    arrayList->size++;
    return 1;
}

int get(ArrayList *arrayList, int index)
{
    return arrayList->data[index];
}

void freeList(ArrayList *arrayList)
{
    free(arrayList->data);
    free(arrayList);
}
#endif